package com.project.controller;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.project.bean.OrderBean;
import com.project.bean.ShopBean;
import com.project.bean.UserBean;
import com.project.service.IOrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.util.Map;

@RestController
@RequestMapping("order")
public class OrderController {
    @Autowired
    private IOrderService service;

    @RequestMapping("submit")
    public String submitOrder(@Valid OrderBean order, BindingResult result, HttpServletRequest request) throws Exception {
        if(result.hasErrors()){
            return new ObjectMapper().writeValueAsString(result.getFieldErrors());
        }

        //得到登陆信息
        UserBean user = (UserBean)request.getSession().getAttribute("loginUser");
        //得到购物车
        Map<Integer, ShopBean> shopMap = (Map<Integer, ShopBean>)request.getSession()
                .getAttribute("shopMap");
        order.setUser(user);
        //调用业务方法，添加订单
        service.addOrder(order, shopMap);

        return "ok";
    }
}
